﻿

using IDEAMS.common;
using IDEAMS.core.deviceClient;
using IDEAMS.core.queue;
using IDEAMS.core.worker;
using IDEAMS.model;
using IDEAMS.model.device;
using IDEAMS.model.setting;
using log4net;
using System;
using System.Collections.Generic;
using System.IO;

namespace IDEAMS.core
{
    public enum AppStatus
    {
        STARTED,
        QUIT
    }
    public class TW_App
    {
        private static ILog logger = LogManager.GetLogger(typeof(TW_App));

        public static string TITLE = "智能设备老化监测系统";
        //public static string VERSION = "1.0.0";
        public static string VERSION = "1.0.1";  // 完善监测逻辑

        public static string COMPANY_NAEM = "北京通为科技有限公司";

        public static AppStatus appStatus = AppStatus.STARTED;


        /// <summary>
        /// 全局配置文件
        /// </summary>
        public static GlobalSetting globalSetting;

        /// <summary>
        /// 文件管理类
        /// </summary>
        public static FileManager fileManager;

        public static WorkerManager workerManager = new WorkerManager();

        /// <summary>
        /// 标准具文件
        /// </summary>
        public static EtalonCollection etalonCollection;

        public static DeviceInfoCollection deviceInfoCollection;
        public static DeviceClientManager deviceClientManager = new DeviceClientManager();

        public static DelegateCollection delegateCollection = new DelegateCollection();

        /// <summary>
        /// 烤机记录
        /// </summary>
        public static RoasterRecordCollection roasterRecordCollection;

        public TW_App() { }

        public static int Init()
        {
            fileManager = new FileManager();

            var fi = new FileInfo(fileManager.logConfigFile);
            log4net.Config.XmlConfigurator.Configure(fi);

            globalSetting = new GlobalSetting();
            int rn2 = globalSetting.Load();
            if(rn2 == -1)
            {
                string errmsg = string.Format("全局配置加载失败");
                logger.ErrorFormat(errmsg);
                return -3;
            }

            etalonCollection = new EtalonCollection();
            etalonCollection.Load();

            deviceInfoCollection = new DeviceInfoCollection();
            deviceInfoCollection.Load();

            deviceInfoCollection.ForEach(x =>
            {
                x.alarmInfoCollection.Load(x.serialNo);
                return false;
            });

            CreateAllDeviceClients(deviceInfoCollection);

            //StartAllDeviceClients(deviceInfoCollection);

            roasterRecordCollection = new RoasterRecordCollection();
            roasterRecordCollection.Load();

            return 0;
        }

        public static void Wait(int miliseconds)
        {
            foreach (var wk in workerManager.workers)
            {
                wk.Value.Join(miliseconds);
            }

            foreach (var client in deviceClientManager.clientList)
            {
                client.Value.dataWorker.Join(miliseconds);
            }
        }
        public static void ProgramQuit()
        {
            StopAllDeviceClients();
            //StopDebugDevice();
            StopAlarmWorker();
        }

        private static string alarmWorkerKey = "";
        private static void StartAlarmWorker()
        {
            //启动AlarmWorker
            System.Guid guid = new Guid();
            guid = Guid.NewGuid();
            alarmWorkerKey = guid.ToString(); ;

            AlarmWorker alarmWorker = new AlarmWorker();
            alarmWorker.StartAsync();
            workerManager.Add(alarmWorkerKey, alarmWorker);

            logger.InfoFormat("报警Worker启动");
        }

        private static void StopAlarmWorker()
        {
            Worker worker = workerManager.Find(alarmWorkerKey);
            if (worker != null)
            {
                worker.Stop();
                workerManager.Delete(alarmWorkerKey);
                worker.Join(3000);
            }

            logger.InfoFormat("报警Worker停止");
        }

        public static AlarmWorker GetAlarmWorker()
        {
            AlarmWorker worker = (AlarmWorker)workerManager.Find(alarmWorkerKey);
            return worker;
        }

        private static void StopAllDeviceClients()
        {
            List<DeviceClient> joinClients = new List<DeviceClient>();
            foreach (var v in deviceClientManager.clientList)
            {

                DeviceClient client = v.Value;
                client.dataWorker.OPMStop_SendOnly();
                client.StopContinuous();
                client.Stop();
                joinClients.Add(client);
                logger.InfoFormat("设备({0})断开中", client.ip);
            }

            foreach (var v in joinClients)
            {
                v.Join(3000);
                logger.InfoFormat("设备({0})断开", v.ip);
            }

            deviceClientManager.clientList.Clear();
        }

        private static void CreateAllDeviceClients(DeviceInfoCollection devices)
        {
            //foreach (var v in devices.deviceList)
            devices.ForEach(v =>
            {
                DeviceClient client = new DeviceClient(v.ip, v.port);
                if (client == null)
                {
                    logger.ErrorFormat("设备[{0}]创建失败", v.serialNo);
                    //continue;
                    return false; //继续
                }
                else
                {
                    TW_App.deviceClientManager.Add(v.serialNo, client);
                }

                return false;//不退出继续

            });
        }

        public static void StartAllDeviceClients(DeviceInfoCollection devices)
        {
            //foreach (var v in devices.deviceList)
            devices.ForEach(v =>
            {
                DeviceClient client = deviceClientManager.Find(v.serialNo);
                if (client == null)
                {
                    logger.ErrorFormat("设备[{0}]创建失败", v.serialNo);
                    //continue;
                    return false; //继续
                }
                else
                {
                    int rn = client.StartAsync(new Action<DeviceParam,int>((DeviceParam deviceParam,int frequency) =>
                    {
                        if (deviceParam != null)
                        {
                            client.deviceParam = new DeviceParam(deviceParam);
                            delegateCollection.SyncSendDeviceParam(deviceParam);
                        }
                        if (frequency != 0)
                        {
                            client.frequency = frequency;
                            delegateCollection.SyncSendDeviceFrequency(v.serialNo,frequency);
                        }
                    }));
                    if (rn != 0)
                    {
                        string errMsg = string.Format("设备({0})连接失败", v.serialNo);
                        logger.ErrorFormat(errMsg);
                    }
                    else
                    {
                        // TW_App.deviceClientManager.Add(v.name, client);
                        logger.InfoFormat("设备({0}连接", client.ip);
                    }
                }

                return false;//不退出继续

            });
        }
    }
}
